<?php
/**
 * 线下红包运营活动
 * Created by PhpStorm.
 * User: Min
 * Date: 2018/3/28
 * Time: 17:02
 */

namespace SDXApi\Controller;


use SDXApi\Model\OrderinfoModel;
use Think\Exception;

class LineActivityBonusController extends AppController
{
    /**
     * 红包id配置
     * @var array
     */
    protected $bonus_id_config = array(
        '2018-03-31' => array('line' => 1102, 'all' =>  1103),
        '2018-04-01' => array('line' => 1078, 'all' =>  1079),
        '2018-04-02' => array('line' => 1080, 'all' =>  1081),
        '2018-04-03' => array('line' => 1082, 'all' =>  1083),
        '2018-04-04' => array('line' => 1084, 'all' =>  1085),
        '2018-04-05' => array('line' => 1086, 'all' =>  1087),
        '2018-04-06' => array('line' => 1088, 'all' =>  1089),
        '2018-04-07' => array('line' => 1090, 'all' =>  1091),
        '2018-04-08' => array('line' => 1092, 'all' =>  1093),
        '2018-04-09' => array('line' => 1094, 'all' =>  1095),
        '2018-04-10' => array('line' => 1132, 'all' =>  1127),
        '2018-04-11' => array('line' => 1134, 'all' =>  1133),
        '2018-04-12' => array('line' => 1136, 'all' =>  1135),
        '2018-04-13' => array('line' => 1138, 'all' =>  1137),
        '2018-04-14' => array('line' => 1140, 'all' =>  1139),
        '2018-04-15' => array('line' => 1142, 'all' =>  1141),
        '2018-04-16' => array('line' => 1144, 'all' =>  1143),
        '2018-04-17' => array('line' => 1146, 'all' =>  1145),
        //'2018-04-17' => array('line' => 201, 'all' =>  202),
        '2018-04-18' => array('line' => 1148, 'all' =>  1147),
        '2018-04-19' => array('line' => 1150, 'all' =>  1149),
        '2018-04-20' => array('line' => 1152, 'all' =>  1151),
        '2018-04-21' => array('line' => 1154, 'all' =>  1153),
        '2018-04-22' => array('line' => 1156, 'all' =>  1155),
    );


    /**
     * @var
     */
    protected $orderModel;

    /**
     * @var
     */
    protected $bonus_type;

    /**
     * @author Min
     * @param string $apptoken
     * @param string $apptime
     */
    public function _initialize($apptoken, $apptime) {
        parent::_initialize ( $apptoken, $apptime );
        $this->orderModel = new OrderinfoModel();
    }

    /**
     * 领取红包
     * @author Min
     */
    public function receive_bonus()
    {
        $fromUrl = I('post.fromUrl');  //code:扫码 share:分享
        $user_id = I('post.uid', 0, 'int');
        $shareData = I('post.shareData', ''); //分享日期

        if (!in_array($fromUrl, array('code', 'share')) || empty($fromUrl) || empty($user_id)) {
            returnApiError('参数有误');
        }

        try {
            //获取红包id
            $bonus_id = $this->get_today_bonus_id($user_id, $fromUrl, $shareData);

            $data = $this->send_bonus($user_id, $bonus_id);
            $data['bonus_type'] = $this->bonus_type;
            returnApiSuccess($data);

        } catch (Exception $e) {
            returnApiError($e->getMessage());
        }

    }

    /**
     * 检查当天是否有领取红包
     * @author Min
     */
    public function check_today_bonus_receive()
    {
        $user_id = I('post.uid', 0, 'int');

        //echo local_date('Y-m-d H:i:s', 1522294800);exit;

        if ( empty($user_id)) {
            returnApiError('参数有误');
        }

        $res = $this->check_get_bonus($user_id);

        if ($res) {
            $bonus = array_flip($this->bonus_id_config[date('Y-m-d')]);
            returnApiError('已领取过红包', array('bonus_type' => $bonus[$res['bonus_type_id']]));

        } else {
            returnApiSuccess(null, '当天未领取红包');

        }

    }


    /**
     * 发送红包
     * @author Min
     * @param $user_id
     * @param $bonus_id
     * @return bool
     * @throws Exception
     */
    protected function send_bonus($user_id, $bonus_id){
        if($this->check_get_bonus($user_id)){
            throw new Exception('已领取过红包');

        } else {

            $res = D('Userbonus')->auto_get_bonus($bonus_id, $user_id);

            if ($res['error'] == 1) {
                throw new Exception($res['msg']);
            }

            return $res;
        }
    }

    /**
     * 检查是否已领取
     * @author Min
     * @param $user_id
     * @return mixed
     */
    private function check_get_bonus($user_id){
        $where = array(
            'user_id' => $user_id,
            'bonus_type_id' => array('in', $this->get_bonus_ids()),
            'get_time' => array('egt', local_strtotime(date('Y-m-d')))
        );

        return M("user_bonus")->field('bonus_type_id')->where($where)->find();
    }

    /**
     * 获取当天红包id
     * @author Min
     * @param $user_id
     * @param $fromUrl
     * @param $shareData
     * @return mixed
     * @throws Exception
     */
    protected function get_today_bonus_id($user_id, $fromUrl, $shareData)
    {
        $today = date('Y-m-d');
        $key = 'all';

        //扫码进入 检查当天是否有支付记录订单
        if ($fromUrl == 'code') {
            if (! $this->check_today_pay_order($user_id)) {
                throw new Exception('今天还没获得领取资格');
            }
        }

        //判断是否新用户
        $isNewUser = $this->orderModel->isNewUser($user_id);

        //扫码进入并且是老用户 领取线下红包
        if ($fromUrl == 'code' && $isNewUser != 1) {
            $key = 'line';
        }

        //分享进入
        if ($fromUrl == 'share') {
            if ($shareData != $today && ! $this->check_today_pay_order($user_id)) {
                throw new Exception('当天未下单，不能领取非当天分享的的红包');
            }
        }

        $bonus_id = $this->bonus_id_config[$today][$key];

        if (empty($bonus_id)) {
            throw new Exception('当天红包id未配置');
        }

        $this->bonus_type = $key;

        return $bonus_id;
    }

    /**
     * 检查用户当天订单
     * @author Min
     * @param $user_id
     * @return bool
     */
    protected function check_today_pay_order($user_id)
    {
        $where = array(
            'user_id' => $user_id,
            'pay_status' => array("in", "2,3"),
            'add_time' => array('egt', local_strtotime(date('Y-m-d')))
        );

        $count = M('order_info')->where($where)->count();

        if (! $count) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * @author Min
     * @return array
     */
    protected function get_bonus_ids()
    {
        $data = array();
        foreach ($this->bonus_id_config as $val) {
            $data[] = $val['line'];
            $data[] = $val['all'];
        }

        return array_unique($data);
    }
}